# Tag grapher
# by Cee Pee

from deps import DotGraph
import random
import subprocess
import string
import forumapi

def settings(settings):
	pass

def main(me, options, args):
	tag_cloud = me.module.get_attr("Tag").get_tag_cloud(me)
	
	graph_options = {
		"concentrate": True,
		#"fontname": "\"Courier\"",
	}
	if me.site.encoding == "ISO-8859-2":
		graph_options["charset"] = "latin1"
	
	graph = DotGraph.Digraph("tags")
	graph.append(DotGraph.AttrList(graph_options, subject="graph"))
	
	tags = {}
	for tag in tag_cloud:
		print("Looking up tag '{0.name}' with level {1}...".format(*tag))
		add_tag(graph, tags, tag[0])
		level = float(tag[1])
		attrs = {
			"height": level,
			"width": level / 2,
			"fontsize": level * 14.0,
		}
		graph.append(DotGraph.Node(tag[0].name, attrs=attrs))
	
	for (a_tag, tag_set) in tags.items():
		if tag_set:
			graph.append(DotGraph.Edge(graph, DotGraph.ID(a_tag), DotGraph.Subgraph(a_tag, [DotGraph.Node(tag) for tag in list(tag_set)])))
	
	filename = "data/dot/" + "".join(random.sample(string.ascii_lowercase, random.randint(5, 10)))
	print("Filename: " + filename)
	
	f = open(filename, mode="w", encoding=me.site.encoding)
	f.write(graph.parse())
	f.close()
	print("Created graph text.")
	
	subprocess.call("dot -Tpng -O " + filename)
	print("Created graph image.")

def add_tag(graph, tags, tag):
	for thread in tag.threads:
		if thread._tags:
			for a_tag in thread.tags:
				if a_tag.name not in tags:
					tags[a_tag.name] = set()
				
				tags[a_tag.name] |= set([my_tag.name for my_tag in thread.tags if my_tag.name != a_tag.name])

if __name__ == "__main__":
	forumapi.run(main, options=settings, supported_types=["vbulletin"])
